package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.CarDao;
import com.hhs.storage.service.BaseRoleService;
import com.hhs.storage.service.CarFleetService;
import com.hhs.storage.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.ImgService;
import com.hhs.storage.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-21
 */
@Service
@Transactional
public class CarServiceImpl extends ServiceImpl<CarDao, Car> implements CarService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private BaseRoleService roleService;
    @Resource
    private ImgService imgService;
    @Resource
    private CarFleetService carFleetService;
    @Override
    public Map<String, Object> getAll(Car car, InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<Car>();
        //查询
        if(!StringUtils.isEmpty(car.getLicencePlate())){//车牌号
            ew.like("licence_plate",car.getLicencePlate());
        }
        if(!StringUtils.isEmpty(car.getCarFleetId())){//所属车队
            ew.eq("car_fleet_id",car.getCarFleetId());
        }
        //如果用户只是车队长，只能查询自身相关数据
        boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
        if (isCDZ){//如果是车队长，查询条件只能查询与自己相关的车队数据
            //查询下属车队id
            List<CarFleet> carFleetList=
                    carFleetService.list(new QueryWrapper<CarFleet>().eq("principal_id",SysUtil.getLoginUserId(request)));
            List<String> carFleetIds=new ArrayList<>();
            for (int i = 0; i <carFleetList.size() ; i++) {
                CarFleet carFleet=carFleetList.get(i);
                carFleetIds.add(carFleet.getId());
            }
            //查询所属车队的车辆
            ew.in("car_fleet_id",carFleetIds.toArray());
        }
        ew.orderByDesc("create_time");
        Page<Car> result = this.page(new Page<Car>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Car> carList=result.getRecords();
        //设置车辆所属车队
        for (int i = 0; i <carList.size() ; i++) {
            Car temp=carList.get(i);
            CarFleet fleet=carFleetService.getById(temp.getCarFleetId());
            temp.setCarFleet(fleet);
        }
        map.put("rows", carList);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> countTable(Car car, InputParam inputParam) {
        //日期查询个数转换
        if (inputParam.getStartDate()!=null){
            inputParam.setStartTime(inputParam.getStartDate().atStartOfDay());
        }
        if (inputParam.getEndDate()!=null){
            inputParam.setEndTime(LocalDateTime.of(inputParam.getEndDate(), LocalTime.MAX));
        }
        List<Car> list=this.baseMapper.countTable(car,inputParam);
        for (int i = 0; i <list.size() ; i++) {
            Car temp=list.get(i);
            CarFleet carFleet=carFleetService.getById(temp.getCarFleetId());
            temp.setCarFleet(carFleet);
        }
        Long total=this.baseMapper.countTableTotal(car,inputParam);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("total",total);
        map.put("code", 1);

        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(Car car, String deleIdStr, MultipartFile[] drivingPermitList) {
        if(StringUtils.isEmpty(car.getLicencePlate()) ||
                StringUtils.isEmpty(car.getCarFleetId())){
            return ResponseInfo.error("参数错误");
        }
        //如果用户只是车队长，只能查询自身相关数据
        boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
        if (isCDZ){//如果是车队长，新增编辑的车队只能是当前用户所有车队
            QueryWrapper<CarFleet> queryWrapper=new QueryWrapper<CarFleet>();
            queryWrapper.eq("principal_id",SysUtil.getLoginUserId(request));
            queryWrapper.eq("id",car.getCarFleetId());
            int temp=carFleetService.count(queryWrapper);
            if (temp==0){
                return ResponseInfo.error("错误的所属车队");
            }
        }
        //车牌都大写
        car.setLicencePlate(car.getLicencePlate().toUpperCase());
        //新增
        if (StringUtils.isEmpty(car.getId())) {
            return add(car, drivingPermitList);
        } else {//修改
            return edit(car, deleIdStr, drivingPermitList);
        }
    }
    private Map<String, Object> edit(Car car, String deleIdStr, MultipartFile[] drivingPermitList) {
        QueryWrapper<Car> queryWrapper=new QueryWrapper<>();
        //车牌号不可重复
        queryWrapper.eq("licence_plate",car.getLicencePlate()).ne("id",car.getId());
        int total=this.count(queryWrapper);
        if (total > 0) {
            return ResponseInfo.error("车牌号已存在，请重新输入");
        }

        //写入司机对象到数据库
        this.updateById(car);
        //行驶证有图片则保存图片
        if(drivingPermitList.length>0){
            imgService.upload( SysUtil.DRIVING_PERMIT,car.getId(),drivingPermitList);
        }

        //删除图片
        if(!StringUtils.isEmpty(deleIdStr)){
            String[] deleIdArr = deleIdStr.split(",");
            if(deleIdArr.length>0){
                for (String id : deleIdArr) {
                    imgService.deleById(id);
                }
            }
        }
        return ResponseInfo.success("编辑成功");
    }

    private Map<String, Object> add(Car car, MultipartFile[] drivingPermitList) {
        QueryWrapper<Car> queryWrapper=new QueryWrapper<>();
        //车牌号不可重复
        queryWrapper.eq("licence_plate",car.getLicencePlate());
        int total=this.count(queryWrapper);
        if (total > 0) {
            return ResponseInfo.error("车牌号已存在，请重新输入");
        }
        //新增车辆信息
        car.setCreateTime(LocalDateTime.now());
        car.setId(SysUtil.UUID());

        //行驶证有图片则保存图片
        if(drivingPermitList.length>0){
            imgService.upload( SysUtil.DRIVING_PERMIT,car.getId(),drivingPermitList);
        }

        this.save(car);
        return ResponseInfo.success("新增成功");
    }
    @Override
    public Map<String, Object> dele(String id) {
        this.baseMapper.deleteById(id);
        //找到司机的图片，删除图片
        Img img = new Img();
        img.setMainId(id);
        List<Img> imgList = imgService.getByMainId(img);
        for (Img img1 : imgList) {
            imgService.deleById(img1.getId());
        }
        return ResponseInfo.success("删除成功");
    }

    @Override
    public Map<String, Object> changeState(String id, Integer state) {
        if (SysUtil.CAR_STATE_MAP.get(state)==null){
            return ResponseInfo.error("错误的参数");
        }
        UpdateWrapper<Car> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("state",state);
        this.update(updateWrapper);
        return ResponseInfo.success();
    }
}
